const mongoose = require('./index');

// 1. 用户表 - 存储医生和患者基本信息
const userSchema = new mongoose.Schema({
  userId: { 
    type: String, 
    required: true, 
    unique: true,
    index: true
  },
  name: { 
    type: String, 
    required: true 
  },
  userType: { 
    type: String, 
    enum: ['doctor', 'patient'], 
    required: true 
  },
  department: { 
    type: String,
    required: function() { return this.userType === 'doctor'; }
  },
  avatar: { 
    type: String, 
    default: '' 
  },
  phone: { 
    type: String, 
    default: '' 
  },
  status: { 
    type: String, 
    enum: ['active', 'inactive'], 
    default: 'active' 
  }
}, { 
  timestamps: true 
});

// 2. 就诊记录表 - 患者看过哪些医生（聊天权限依据）
const visitSchema = new mongoose.Schema({
  visitId: { 
    type: String, 
    required: true, 
    unique: true 
  },
  patientId: { 
    type: String, 
    required: true,
    index: true
  },
  doctorId: { 
    type: String, 
    required: true,
    index: true
  },
  visitDate: { 
    type: Date, 
    required: true 
  },
  department: { 
    type: String, 
    required: true 
  },
  diagnosis: { 
    type: String, 
    default: '' 
  },
  visitType: { 
    type: String, 
    enum: ['first_visit', 'follow_up', 'emergency'], 
    default: 'first_visit' 
  },
  status: { 
    type: String, 
    enum: ['completed', 'cancelled'], 
    default: 'completed' 
  }
}, { 
  timestamps: true 
});

// 3. 消息表 - 统一存储所有聊天记录
const messageSchema = new mongoose.Schema({
  roomId: { 
    type: String, 
    required: true,
    index: true
  },
  senderId: { 
    type: String, 
    required: true 
  },
  senderType: { 
    type: String, 
    enum: ['doctor', 'patient'], 
    required: true 
  },
  content: { 
    type: String, 
    // required: true 
  },
  messageType: { 
    type: String, 
    enum: ['text', 'image', 'file', 'voice'], // LHX聊天模块 - 添加语音消息类型
    default: 'text' 
  },
  timestamp: { 
    type: Date, 
    default: Date.now 
  },
  status: { 
    type: String, 
    enum: ['sent', 'delivered', 'read'], 
    default: 'sent' 
  },
  // 文件信息（当messageType为file、image或voice时）
  fileInfo: {
    fileName: { type: String, default: '' },
    fileSize: { type: Number, default: 0 },
    fileUrl: { type: String, default: '' },
    mimeType: { type: String, default: '' },
    duration: { type: Number, default: 0 } // LHX聊天模块 - 语音时长（秒）
  }
}, { 
  timestamps: true 
});

// 创建复合索引提高查询效率
userSchema.index({ userId: 1, userType: 1 });
userSchema.index({ userType: 1, department: 1 });

visitSchema.index({ patientId: 1, visitDate: -1 });
visitSchema.index({ doctorId: 1, visitDate: -1 });
visitSchema.index({ patientId: 1, doctorId: 1 });

messageSchema.index({ roomId: 1, timestamp: -1 });
messageSchema.index({ senderId: 1, timestamp: -1 });
messageSchema.index({ roomId: 1, status: 1 });

// 4. 聊天权限表 - 管理患者与医生之间的聊天权限
const chatPermissionSchema = new mongoose.Schema({
  patientId: {
    type: String,
    required: true,
    index: true
  },
  doctorId: {
    type: String,
    required: true,
    index: true
  },
  permissionType: {
    type: String,
    enum: ['allowed', 'blocked', 'auto'],
    required: true,
    default: 'auto'
  },
  source: {
    type: String,
    enum: ['manual', 'registration', 'visit', 'default'],
    required: true,
    default: 'default'
  },
  isActive: {
    type: Boolean,
    default: true
  },
  metadata: {
    reason: String,           // 设置原因
    registrationId: String,   // 关联的挂号ID（如果来源是挂号）
    visitId: String          // 关联的就诊ID（如果来源是就诊）
  },
  createdAt: {
    type: Date,
    default: Date.now,
    index: true
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
}, { 
  timestamps: true 
});

// 复合索引：确保每个患者-医生组合只有一条有效记录
chatPermissionSchema.index({ patientId: 1, doctorId: 1, isActive: 1 }, { unique: true });

// 更新时间中间件
chatPermissionSchema.pre('save', function(next) {
  this.updatedAt = new Date();
  next();
});

// 创建模型
const LhxUser = mongoose.model('LhxUser', userSchema);
const LhxVisit = mongoose.model('LhxVisit', visitSchema);
const LhxMessage = mongoose.model('LhxMessage', messageSchema);
const LhxChatPermission = mongoose.model('LhxChatPermission', chatPermissionSchema);

module.exports = {
  LhxUser,
  LhxVisit,
  LhxMessage,
  LhxChatPermission
};